<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Engine\WebSocket\Frame;
use Hyperf\Engine\WebSocket\Response;
use Hyperf\WebSocketServer\Constant\Opcode;
use Swoole\Server;
use Hyperf\WebSocketServer\Context;
use Swoole\WebSocket\Server as WebSocketServer;
use Hyperf\Context\ApplicationContext;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    protected $redis;

    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
    }

    public function onMessage($server, $frame): void
    {
        $friendId = Context::get('friendId');
        $friendFd = $this->redis->get($friendId);
        $server->push($frame->fd, $frame->data);  // 发给自己
        if ($server->exist(intval($friendFd))) {  // 朋友是否上线了
            $server->push(intval($friendFd), $frame->data);  // 发给朋友
        }
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        var_dump($fd . '离开了');
    }

    public function onOpen($server, $request): void
    {
        $userId = $request->get['userId'];
        $friendId = $request->get['friendId'];
        if (!$userId) {
            var_dump('用户id缺失');
        }
        if (!$friendId) {
            var_dump('朋友id缺失');
        }
        var_dump($request->fd . '进来了，用户id：' . $userId . '，朋友id：' . $friendId);

        $this->redis->set($userId, $request->fd);
        Context::set('friendId', $friendId);
    }
}
